package com.mydemo.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.mydemo.common.Constant;
import com.mydemo.common.exception.captcha.CaptchaException;
import com.mydemo.common.pojo.RespResult;
import com.mydemo.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author Last_Island
 * @version 1.0
 */
@Service
public class SysCaptchaService {
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private EmailService emailService;

    /**
     * 获取图片验证码
     *
     * @return
     */
    public RespResult getImgCaptcha() {
        LineCaptcha lineCaptcha = generateCaptcha();
        String uuid = IdUtil.fastSimpleUUID();
        String code = lineCaptcha.getCode();
        String img = lineCaptcha.getImageBase64Data();
        String key = Constant.SYS_CAPTCHA_KEY+uuid;
        redisUtils.setCacheObject(key, code, 5, TimeUnit.MINUTES);
        RespResult success = RespResult.success("获取验证码成功");
        success.put("uuid", uuid);
        success.put("captcha", img);
        return success;
    }

    /**
     * 获取邮箱验证码
     *
     * @return
     */
    public RespResult getEmailCaptcha(String email) {
        String key = Constant.SYS_CAPTCHA_KEY + email;
        long expire = redisUtils.getExpire(key);
        long cooldown = expire - 4 * 60;
        if (expire != 0 && cooldown > 0) {
            return RespResult.custom(601,"验证码发送中，请耐心等待", cooldown);
        }
        LineCaptcha lineCaptcha = generateCaptcha();
        String code = lineCaptcha.getCode();
        redisUtils.setCacheObject(key, code, 5, TimeUnit.MINUTES);
        emailService.sendEmail(email, "验证码", code);
        return RespResult.success("获取验证码成功");
    }

    /**
     * 自定义生成验证码
     *
     * @return
     */
    public LineCaptcha generateCaptcha() {
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        return CaptchaUtil.createLineCaptcha(200, 100, randomGenerator, 150);
    }

    /**
     * 检查验证码
     *
     * @param uuid
     * @param code
     * @return
     */
    public void checkCaptcha(String uuid, String code) {
        String cache = redisUtils.getCacheObject(Constant.SYS_CAPTCHA_KEY + uuid);
        try{
            if (!StringUtils.hasText(cache)){
                throw new CaptchaException("验证码已过期");
            }else if (!cache.equals(code)){
                throw new CaptchaException("验证码错误");
            }
        }finally {
            redisUtils.deleteObject(Constant.SYS_CAPTCHA_KEY + uuid);
        }
    }

}
